package cn.toe.dao.Impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import cn.toe.bean.Administrators;
import cn.toe.bean.Article;
import cn.toe.dao.AdministratorsDao;

@Repository
public class AdministratorsDaoImp implements AdministratorsDao {

	@Autowired
	private SessionFactory sessionFactory;	
	
	@Override
	public void addAdministrators(Administrators administrators) {
		// TODO Auto-generated method stub
		sessionFactory.getCurrentSession().save(administrators);
	}

	@Override
	public List<Administrators> getAllAdministrators() {
		// TODO Auto-generated method stub
		String hql = "from Administrators";
		Query query = sessionFactory.getCurrentSession().createQuery(hql);
		return query.list();
	}

	@Override
	public boolean delAdministrators(Integer id) {
		// TODO Auto-generated method stub
		String hql = "delete Administrators a where a.adminid=?";
		Query query = sessionFactory.getCurrentSession().createQuery(hql);
		query.setInteger(0, id);
		return (query.executeUpdate() > 0);
	}

	@Override
	public Administrators getAdministrators(Integer id) {
		// TODO Auto-generated method stub
		String hql = "from Administrators a where a.adminid=?";
		Query query = sessionFactory.getCurrentSession().createQuery(hql);//此时使用的是hql语句
		query.setInteger(0, id);
		return (Administrators) query.uniqueResult();
	}

	@Override
	public Administrators getAdministratorsByName(String name) {
		// TODO Auto-generated method stub
		String hql = "from Administrators a where a.adname=?";
		Query query = sessionFactory.getCurrentSession().createQuery(hql);//此时使用的是hql语句
		query.setString(0, name);
		return (Administrators) query.uniqueResult();
	}
	
	@Override
	public boolean updateAdministrators(Administrators administrators) {
		// TODO Auto-generated method stub
		String hql = "update Administrators a set a.adname=:adname,a.role=:role,a.passWord=:passWord,a.documentType=:documentType,a.documentId=:documentId,a.email=:email,a.tphone=:tphone where a.adminid=:adminid";
		Query query = sessionFactory.getCurrentSession().createQuery(hql);
		query.setString("adname",administrators.getAdname());
		if(administrators.getRole()==null){
			query.setBigInteger("role",null);
		}else{
			query.setInteger("role",administrators.getRole().getRole());
		}
		query.setString("passWord",administrators.getPassWord());
		query.setString("documentType",administrators.getDocumentType());
		query.setString("documentId",administrators.getDocumentId());
		query.setString("email",administrators.getEmail());
		query.setString("tphone",administrators.getTphone());
		query.setInteger("adminid",administrators.getAdminid());
		System.out.println(query.executeUpdate());
		return (query.executeUpdate() > 0);
	}

	

}
